<template>
  <div class="result-container">
    <div class="result-header">
      <button class="back-button" @click="goBack">← 返回</button>
      <h1>测评结果</h1>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button class="retry-button" @click="fetchResult">重试</button>
    </div>

    <div v-else class="result-content">
      <div class="result-summary">
        <h2>{{ result.assessmentTitle }}</h2>
        <div class="summary-meta">
          <span>完成时间: {{ formatDate(result.completedAt) }}</span>
          <span>用时: {{ result.duration }}分钟</span>
        </div>
        <div class="total-score">
          <span class="score-label">总得分</span>
          <span class="score-value">{{ result.totalScore }}</span>
          <span class="score-max">/ {{ result.maxScore }}</span>
        </div>
        <div class="score-description">
          <p>{{ result.scoreDescription }}</p>
        </div>
      </div>

      <div class="dimensions-container">
        <h3>各维度得分</h3>
        <div class="dimensions-list">
          <div
            v-for="(score, dimension) in result.dimensions"
            :key="dimension"
            class="dimension-item"
          >
            <div class="dimension-header">
              <span class="dimension-name">{{ dimension }}</span>
              <span class="dimension-score">{{ score }}分</span>
            </div>
            <div class="dimension-bar">
              <div
                class="dimension-bar-fill"
                :style="{
                  width: getDimensionPercentage(score, dimension) + '%',
                  backgroundColor: getDimensionColor(score, dimension),
                }"
              ></div>
            </div>
            <p class="dimension-description">{{ getDimensionDescription(dimension, score) }}</p>
          </div>
        </div>
      </div>

      <div class="recommendations">
        <h3>建议与干预</h3>
        <ul class="recommendation-list">
          <li v-for="(recommendation, index) in result.recommendations" :key="index">
            <span class="recommendation-icon">•</span>
            <span class="recommendation-text">{{ recommendation }}</span>
          </li>
        </ul>
      </div>

      <div class="result-actions">
        <button class="share-button" @click="shareResult">分享结果</button>
        <button class="save-button" @click="saveResult">保存结果</button>
        <button class="new-assessment-button" @click="startNewAssessment">开始新测评</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { resultAPI } from '@/utils/api'

export default {
  name: 'ResultView',
  setup() {
    const router = useRouter()
    const route = useRoute()

    const resultId = route.params.id
    const result = ref({})
    const loading = ref(true)
    const error = ref('')



    // 获取测评结果
    const fetchResult = async () => {
      loading.value = true
      error.value = ''
      try {
        // 从API获取结果
        const response = await resultAPI.getResultById(resultId)
        
        // 格式化结果数据以适应前端展示
        result.value = {
          id: response.id,
          assessmentTitle: response.assessmentTitle || '心理测评',
          completedAt: response.createdAt || new Date().toISOString(),
          duration: response.duration || 0,
          totalScore: response.score || 0,
          maxScore: response.maxScore || 100,
          scoreDescription: response.description || '您的测评已完成，感谢参与。',
          dimensions: response.dimensions || {},
          recommendations: response.recommendations || []
        }
      } catch (err) {
        error.value = '加载测评结果失败'
        console.error('Failed to fetch result:', err)
        // 提供一个基本的空数据结构，确保页面不会崩溃
        result.value = {
          id: resultId,
          assessmentTitle: '心理测评',
          completedAt: new Date().toISOString(),
          duration: 0,
          totalScore: 0,
          maxScore: 100,
          scoreDescription: '加载结果失败，请稍后重试。',
          dimensions: {},
          recommendations: []
        }
      } finally {
        loading.value = false
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 获取维度得分百分比
    const getDimensionPercentage = (score, dimension) => {
      // 根据不同维度设定不同的满分标准
      const dimensionMaxScores = {
        考试焦虑: 25,
        学业压力: 25,
        情绪管理: 25,
        人际关系: 25,
        焦虑: 20,
        抑郁: 20,
        压力应对: 30,
        心理韧性: 30,
      }

      const maxScore = dimensionMaxScores[dimension] || 50
      return Math.min((score / maxScore) * 100, 100)
    }

    // 获取维度颜色（根据得分判断严重程度）
    const getDimensionColor = (score, dimension) => {
      const percentage = getDimensionPercentage(score, dimension)

      if (percentage < 30) {
        return '#4caf50' // 绿色 - 良好
      } else if (percentage < 60) {
        return '#ff9800' // 橙色 - 一般
      } else {
        return '#f44336' // 红色 - 需关注
      }
    }

    // 获取维度描述
    const getDimensionDescription = (dimension, score) => {
      const percentage = getDimensionPercentage(score, dimension)

      if (percentage < 30) {
        return `${dimension}水平良好，继续保持。`
      } else if (percentage < 60) {
        return `${dimension}水平一般，有一定的改善空间。`
      } else {
        return `${dimension}水平需要关注，建议采取相应措施进行调整。`
      }
    }

    // 分享结果
    const shareResult = () => {
      // 在实际应用中，这里可以实现分享到社交媒体的功能
      alert('分享功能开发中...')
    }

    // 保存结果
    const saveResult = () => {
      // 在实际应用中，这里可以实现保存结果到本地或云端的功能
      alert('结果已保存！')
    }

    // 开始新测评
    const startNewAssessment = () => {
      router.push('/assessment')
    }

    // 返回上一页
    const goBack = () => {
      router.push('/assessment')
    }

    onMounted(() => {
      fetchResult()
    })

    return {
      resultId,
      result,
      loading,
      error,
      fetchResult,
      formatDate,
      getDimensionPercentage,
      getDimensionColor,
      getDimensionDescription,
      shareResult,
      saveResult,
      startNewAssessment,
      goBack,
    }
  },
}
</script>

<style scoped>
.result-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.result-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.back-button {
  position: absolute;
  left: 20px;
  top: 0;
  background: none;
  border: none;
  font-size: 16px;
  color: #61dafb;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(97, 218, 251, 0.1);
}

.result-header h1 {
  font-size: 32px;
  color: #333;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(97, 218, 251, 0.3);
  border-top: 3px solid #61dafb;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.retry-button {
  background: #61dafb;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s ease;
}

.retry-button:hover {
  background: #4fc0e8;
}

.result-content {
  max-width: 1000px;
  margin: 0 auto;
}

.result-summary {
  background: white;
  border-radius: 16px;
  padding: 40px;
  text-align: center;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.result-summary h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 15px;
}

.summary-meta {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 30px;
  font-size: 14px;
  color: #666;
}

.total-score {
  margin-bottom: 20px;
}

.score-label {
  font-size: 18px;
  color: #666;
  margin-right: 10px;
}

.score-value {
  font-size: 48px;
  font-weight: bold;
  color: #61dafb;
  margin-right: 10px;
}

.score-max {
  font-size: 24px;
  color: #999;
}

.score-description {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  max-width: 600px;
  margin: 0 auto;
}

.dimensions-container {
  background: white;
  border-radius: 16px;
  padding: 40px;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.dimensions-container h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.dimensions-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.dimension-item {
  padding: 20px;
  border-radius: 12px;
  background: #f9f9f9;
  transition: all 0.3s ease;
}

.dimension-item:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.dimension-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dimension-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.dimension-score {
  font-size: 16px;
  font-weight: bold;
  color: #61dafb;
}

.dimension-bar {
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  margin-bottom: 10px;
  overflow: hidden;
}

.dimension-bar-fill {
  height: 100%;
  transition: width 1s ease;
  border-radius: 4px;
}

.dimension-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.recommendations {
  background: white;
  border-radius: 16px;
  padding: 40px;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.recommendations h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.recommendation-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.recommendation-list li {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
  line-height: 1.6;
}

.recommendation-icon {
  color: #61dafb;
  font-size: 20px;
  margin-right: 10px;
  margin-top: 2px;
  flex-shrink: 0;
}

.recommendation-text {
  flex-grow: 1;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.share-button,
.save-button,
.new-assessment-button {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.share-button {
  background: #f0f0f0;
  color: #666;
}

.share-button:hover {
  background: #e0e0e0;
}

.save-button {
  background: #4caf50;
  color: white;
}

.save-button:hover {
  background: #45a049;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.new-assessment-button {
  background: linear-gradient(135deg, #61dafb 0%, #4fc0e8 100%);
  color: white;
}

.new-assessment-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(97, 218, 251, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-container {
    padding: 10px;
  }

  .back-button {
    left: 10px;
    top: 10px;
    padding: 6px 12px;
    font-size: 14px;
  }

  .result-header h1 {
    font-size: 24px;
    margin-top: 40px;
  }

  .result-summary,
  .dimensions-container,
  .recommendations {
    padding: 25px;
  }

  .result-summary h2 {
    font-size: 22px;
  }

  .summary-meta {
    flex-direction: column;
    gap: 10px;
  }

  .score-value {
    font-size: 36px;
  }

  .score-max {
    font-size: 20px;
  }

  .dimensions-container h3,
  .recommendations h3 {
    font-size: 20px;
  }

  .dimension-name {
    font-size: 16px;
  }

  .recommendation-list li {
    font-size: 14px;
  }

  .result-actions {
    flex-direction: column;
    gap: 15px;
  }

  .share-button,
  .save-button,
  .new-assessment-button {
    width: 100%;
    padding: 12px 20px;
    font-size: 14px;
  }
}
</style>
